<template>
    <a-layout class="main">
        <div class="query">
            <a-button class="btn" v-if="isHasPermission()('sys.role.save')" type="primary" @click="() => {addModalVisible = true;selectedKeys.length = 0}">新增</a-button><a-button v-show="selectedRowKeys.length > 0 && isHasPermission()('sys.role.delete')" class="btn" type="danger" @click="deleteData">删除</a-button>
        </div>
        <a-table :locale="{'emptyText':'暂无数据'}" :loading="loading" rowKey="id" :defaultExpandAllRows="true" :pagination="false" :columns="columns" :dataSource="data" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" >
            <template slot="control" slot-scope="text, record">
                <a-tag color="#2db7f5" v-if="isHasPermission()('sys.role.update')" @click="update(record)">修改</a-tag>
            </template>
        </a-table>
        <a-modal
                :title="form.getFieldValue('roleId') ? '修改角色' : '添加角色'"
                :visible="addModalVisible"
                :confirmLoading="addModalLoading"
                :destroyOnClose="true"
                @ok="addMenu"
                :maskClosable="false"
                @cancel="addModalVisible = false"
        >
            <a-spin :spinning="addModalLoading">
                <a-form :form="form" autocomplete="off">

                    <a-form-item
                            label="角色名称"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                    >
                        <a-input v-decorator="['roleName', {rules: [{required: true, message: '请输入角色名称！'}]}]" />
                        <a-input type="hidden" v-decorator="['roleId',{}]" />
                        <a-input type="hidden" v-decorator="['menuIdList',{}]" />
                    </a-form-item>
                    <a-form-item
                            label="备注"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                    >
                        <a-input v-decorator="['remark']" />
                    </a-form-item>
                    <a-form-item
                            label="角色权限"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                    >
                        <a-tree
                                checkable
                                :defaultExpandAll="true"
                                @check="onCheck"
                                :checkedKeys="selectedKeys"
                                :treeData="treeData"
                        />
                    </a-form-item>
                </a-form>
            </a-spin>
        </a-modal>
    </a-layout>
</template>

<script>
    import {mapGetters} from 'vuex'
    import qs from 'qs'
    const columns = [{
        title: 'id',
        dataIndex: 'roleId',
    },{
        title: '角色名称',
        dataIndex: 'roleName',
    }, {
        title: '备注',
        dataIndex: 'remark',
    }, {
        title: '操作',
        dataIndex: 'control',
        scopedSlots: { customRender: 'control' },
    }];
    export default {
        name: "Role",
        data(){
            return {
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 5 }
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 16 }
                },
                selectedRowKeys: [],
                selectedItems:[],
                addModalVisible:false,
                addModalLoading:false,
                loading:false,
                form:this.$form.createForm(this),
                autoExpandParent: true,
                checkedKeys: [47],
                selectedKeys:[],
                treeData:[],
                columns,
                data:[]
            }
        },
        watch: {
            checkedKeys(val) {
                console.log('onCheck', val)
            }
        },
        mounted(){
            if(!this.isHasPermission()('sys.role.list')){
                return
            }
            this.loading = true;
            this.$http.post(this.api.role.list).then(res => {
                this.data = res.page.list
                this.loading = false
            }).catch(err => {
                console.log(err)
            })
            this.$http.post(this.api.menu.list).then(res => {
                let data = this.getTreeData(res)
                console.log(data)
                this.treeData = data
            }).catch(err => {
                console.log(err)
            })
        },
        methods:{
            ...mapGetters(['isHasPermission']),
            getTreeData(originData){
                originData.forEach(item => {
                    item.key = item.menuId
                    item.value = item.menuId+''
                    item.title = item.name
                    if(item.children && item.children.length > 0){
                        this.getTreeData(item.children)
                    }
                })
                return originData
            },
            onSelectChange (selectedRowKeys,selectedItems) {
                this.selectedRowKeys = selectedRowKeys
                this.selectedItems = selectedItems
            },
            onCheck (selectedKeys) {
                const { form: { getFieldsValue,setFieldsValue } } = this
                setFieldsValue({menuIdList:selectedKeys.join(',')})
                this.selectedKeys = selectedKeys
            },
            addMenu(){
                this.addModalLoading = true;
                const { form: { validateFields } } = this
                validateFields((errors, values) => {
                    if (!errors) {
                        values.menuIdList = values.menuIdList.split(',')
                        this.$http({
                            url:this.api.role.saveOrUpdate,
                            method:'post',
                            transformRequest: [function (data, headers) {
                                headers['Content-Type'] = 'application/json;charset=utf-8'
                                return JSON.stringify(qs.parse(data));
                            }],
                            data:values,
                        }).then(res => {
                            this.addOrUpdateHtmlData(res.result);
                            this.addModalLoading = false;
                            this.addModalVisible = false;
                        }).catch(err => {
                            console.log(err)
                        })
                    } else {
                        this.addModalLoading = false
                    }
                })
            },
            addOrUpdateHtmlData(targetData){
                let indexOf = this.indexOf(targetData,this.data,"roleId")
                if(indexOf != -1){
                    this.data[indexOf] = targetData
                    this.$message.success("修改成功！")
                }else{
                    this.data = [targetData].concat(this.data,"roleId")
                    this.$message.success("添加成功！")
                }
            },
            update(record){
                this.addModalVisible = true
                const { form: { setFieldsValue } } = this
                if(record.menuIdList){
                    this.selectedKeys = record.menuIdList
                }else{
                    this.selectedKeys.length = 0
                }
                setTimeout(() => {
                    setFieldsValue({roleId:record.roleId+'',roleName:record.roleName,remark:record.remark,menuIdList:record.menuIdList.join(",")})
                },0)
            },
            deleteData(){
                let arr = [];
                this.selectedItems.forEach(item => {
                    arr.push(item.roleId)
                })
                const self = this
                this.$confirm({
                    title: '删除操作！',
                    content: '您是否要删除选中项？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        return new Promise((resolve, reject) => {
                            self.$http.post(self.api.role.deleteBatch,arr).then(res => {
                                self.$message.success('删除成功！')
                                for(let i in self.selectedItems){
                                    self.deleteHtmlData(self.selectedItems[i],self.data)
                                }
                                self.selectedRowKeys.length = 0
                                resolve()
                            })
                        }).catch(() => console.log('Oops errors!'));
                    },
                    onCancel() {},
                });
            },
            deleteHtmlData(targetData){
                let indexOf = this.indexOf(targetData,this.data,"roleId")
                if(indexOf != -1){
                    this.data.splice(indexOf,1)
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .main{
        padding: 25px;
        background: #fff;
        .query{
            margin-bottom: 25px;
            .btn{
                margin-left: 10px;
            }
        }
    }
</style>
